package cn.nxcoder.jmw.handler;

import cn.nxcoder.jmw.core.BusinessErrorException;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * 全局异常处理Controller
 * @author shengwu ni
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Map<String, String> exceptionHandler(Exception e) {
        Map<String, String> result = Maps.newHashMap();
        if (e instanceof BusinessErrorException) {
            BusinessErrorException exception = (BusinessErrorException) e;
            result.put("code", exception.getCode());
            result.put("msg", exception.getErrorMsg());
        } else {
            result.put("code", "-1");
            result.put("msg", "未知错误,请看日志");
        }
        LOG.error("系统异常\n",e);
        return result;
    }
}
